const sequelize = require('../../common/sequelize')
const { Model } = require('sequelize')
const userSchema = require('./userSchema')
const Student = require('../Student')
const { roleType } = require('../../common/type')
const Class = require('../Class/index')
const Teacher = require('../Teacher')




class User extends Model {

  Student
  Class
  Teacher
  /**
   * @description 用于创建学生信息
   * @param {Object} stuInfo 学生的基本信息
   */
  static async createStudent({ username, password, name, grade, school, tel, qq, email, addr, ClassId }) {
    const res = await User.create({ username, password, role: roleType.STU })
    const id = res.getDataValue('id')
    await Student.create({ name, grade, school, tel, qq, email, addr, ClassId, UserId: id })
  }

  /**
   * @description 用于创建一个老师并将老师信息插入到数据库中
   * @param {Object} 老师的基本信息 
   */
  static async createTeacher({ username, password, name, tel, qq, email, desc }) {
    const res = await User.create({ username, password, role: roleType.TEACHER })
    const id = res.getDataValue('id')
    await Teacher.create({ name, tel, qq, email, desc, UserId: id })
  }

  /**
   * @description 初始换管理员账号
   * @param {Object} config 超级管理员默认账号密码设置
   * @returns null
   */
  static async generateAdmin(config) {
    let admin = await this.findUsersByRoleType(roleType.ADMIN)
    if (admin.length > 0) {
      return
    } else {

      const res = await this.create({ username: config.USERNAME, password: config.PASSWORD, role: roleType.ADMIN })
      console.log(res);
    }
  }

  /**
   * @description 传入一个id，根据id去学生或老师表中查询对应用户的详细信息
   * @param {string} id 用户唯一id
   * @returns 返回一个包含对应用户信息的数据集
   */
  static async findUserById(id) {

    const userRes = (await this.findOne({ where: { id }, attributes: { exclude: ['id'] } })).dataValues

    if (userRes) {
      if (userRes.role & roleType.STU) {
        const res = await Student.getInfoById(userRes.id)
        return res ? Object.assign({ username: userRes.username }, res) : null

      } else if (userRes.role & roleType.TEACHER) {
        // 老师信息
        const res = await Teacher.getInfoById(userRes.id)
        return res ? res : null
      }
    } else {
      return null
    }

  }

  /**
   * @description 通过用户名来查询对应用户的详细信息
   * @param {string} username 用户名
   * @returns 查询的对应用户的个人信息
   */
  static async findUserByUsername(username) {
    const userRes = await User.findOne({ where: { username }, raw: true })
    if (userRes) {
      if (userRes.role & roleType.STU) {
        const res = await Student.getInfoById(userRes.id)
        return res ? Object.assign({ username: userRes.username }, res) : null
      } else if (userRes.role & roleType.TEACHER) {
        // 老师信息
        const res = await Teacher.getInfoById(userRes.id)
        return res ? res : null
      }
      return userRes
    } else {
      return null
    }
  }


  /**
   * @description 传入一个角色身份，在用户表中查询所有与之对应身份的用户信息
   * @param {roleType.*} role roleType中的某一类角色
   * @returns {Array} 包含了所有对应角色的用户信息数据集
   */
  static async findUsersByRoleType(role) {
    let results = []
    if (role & roleType.STU) {
      const res = await this.findAll({
        where: { role: roleType.STU },
        raw: true,
        attributes: {
          exclude: ['password', 'role', 'createdAt']
        }
      })
      const stuRes = await Student.getStudentsInfo({})
      res.forEach(el => {
        const stu = stuRes.find(e => e.UserId == el.id)
        delete stu.UserId
        results.push(Object.assign(el, stu))
      })
    } else if (role & roleType.TEACHER) {
      const res = await this.findAll({
        where: { role: roleType.TEACHER },
        raw: true,
        attributes: {
          exclude: ['password', 'role', 'createdAt']
        }
      })
      const teacherRes = await Teacher.getTeachersInfo()
      res.forEach(el => {
        const teacher = teacherRes.find(e => e.UserId == el.id)
        delete teacher.UserId
        results.push(Object.assign(el, teacher))
      })
    } else if (role & roleType.ADMIN) {
      let res = await this.findAll({
        where: { role: roleType.ADMIN },
        raw: true,
        attributes: {
          exclude: ['password', 'role', 'createdAt']
        }
      })
      results = [...res]
    }
    return results
  }

  static async hasUser(id = '', username = '') {
    if (id === '' && username === '') {
      return null
    }
    if (id !== '') {
      // 根据id查询
      const res = await User.findByPk(id, {
        attributes: {
          exclude: ['password', 'createdAt']
        },
        raw: true
      })
      return res ? res : null
    }
    if (username !== '') {
      // 根据用户名查询
      const res = await User.findOne({
        where: { username },
        exclude: ['password', 'createdAt'],
        raw: true
      })
      return res ? res : null
    }
  }
}


User.init(userSchema, {
  sequelize,
  timestamps: true,
  updatedAt: false,
  modelName: 'User',
  tableName: 'users'
});

module.exports = User
